<script setup>
import { FilterMatchMode, FilterOperator } from 'primevue/api';
import { ref, onBeforeMount } from 'vue';
import axios from '../../util/interceptor';
import { useToast } from "primevue/usetoast";

const toast = useToast();
const selectedStuffs = ref();
const deleteStuffsDialog = ref(false);
const dt = ref();
const submitted = ref(false);
const addStuffDialog = ref(false);
const sysUser = ref(null);
const recruct = ref([])
const deptList = ref(null);
const filters1 = ref(null);
const loading = ref(true);
const editingRows = ref([]);
const stuffs = ref([]);
const statuses = ref([
    { label: '正常(在职)', value: '1' },
    { label: '禁用(离职)', value: '0' }
]);
const genders = ref([
    { label: '男', value: '男' },
    { label: '女', value: '女' }
]);

const getStatusLabel = (status) => {
    switch (status) {
        case 'INSTOCK':
            return 'success';
        case '1':
            return 'success';
        case '0':
            return 'danger';

        case 'LOWSTOCK':
            return 'warning';

        case 'OUTOFSTOCK':
            return 'danger';

        default:
            return null;
    }
};


const onRowEditSave = async (event) => {
    let { newData, index } = event;

    stuffs.value[index] = newData;
    const sysUserUpdateInfo = ref({
        id: stuffs.value[index].id,
        deptId: stuffs.value[index].deptId,
        status: stuffs.value[index].status
    })
    console.log(sysUserUpdateInfo)
    const response = await axios.post("/user/adjustSysUser", sysUserUpdateInfo.value)
    if (response.data.code == 200) {
        toast.add({ severity: 'success', summary: 'Attention', detail: response.data.message, life: 3000 });
        getData();
    }
    /* console.log(stuffs.value[index].username)
    console.log(stuffs.value[index].deptId)
    console.log(stuffs.value[index].status) */
};

const exportCSV = () => {
    dt.value.exportCSV();
};

onBeforeMount(() => {
    loading.value = false;
    getData();
    initFilters1();
});

const getData = async () => {
    const response = await axios.get("/user/getAllUsers/");
    const data = response.data.data
    console.log(data)
    sysUser.value = data
    const dept = await axios.get("/dept/deptList/");
    //console.log(dept.data.data)
    deptList.value = dept.data.data
}

const initFilters1 = () => {
    filters1.value = {
        global: { value: null, matchMode: FilterMatchMode.CONTAINS },
        username: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
        deptId: { operator: FilterOperator.OR, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] },
        status: { operator: FilterOperator.OR, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] },

        /* 'country.name': { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
        representative: { value: null, matchMode: FilterMatchMode.IN },
        date: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.DATE_IS }] }, */
        //id: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] },
        /* status: { operator: FilterOperator.OR, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] },
        activity: { value: [0, 50], matchMode: FilterMatchMode.BETWEEN },
        verified: { value: null, matchMode: FilterMatchMode.EQUALS } */
    };
};

const clearFilter1 = () => {
    initFilters1();
};

const openNew = () => {
    recruct.value = {};
    submitted.value = false;
    addStuffDialog.value = true;
};

const hideDialog = () => {
    addStuffDialog.value = false;
    submitted.value = false;
};

const confirmDeleteSelected = async () => {
    deleteStuffsDialog.value = true;
    /* console.log(sysUser.value.filter(val => selectedStuffs.value.includes(val)))
    console.log(selectedStuffs.value)
    const response = await axios.post("/user/deleteSysUser",selectedStuffs.value);
    console.log(response.data.message); */
};

const deleteStuff = async () => {
    const response = await axios.post("/user/deleteSysUser",selectedStuffs.value);
    toast.add({ severity: 'success', summary: 'Attention', detail: response.data.message, life: 3000 });
    deleteStuffsDialog.value = false;
    selectedStuffs.value = null;
    getData();
}

const saveProduct = async () => {
    submitted.value = true;
    //typeof (recruct.value.name) == 'undefined' || typeof recruct.value.phone == 'undefined' || typeof recruct.value.email == 'undefined' || typeof recruct.value.dept.name == 'undefined' || typeof recruct.value.status.value == 'undefined'
    /* if (!recruct.value.name || !recruct.value.phone || !recruct.value.email || !recruct.value.dept || !recruct.value.status) {
        console.log("shit")
        return;
    } */
    const newStuff = ref({
        username: recruct.value.username,
        password: recruct.value.password,
        realName: recruct.value.realName,
        //email: recruct.value.email,
        phone: recruct.value.phone,
        deptId: recruct.value.dept.id,
        status: recruct.value.status.value,
        realId: recruct.value.realId,
        gender: recruct.value.gender
    });
    console.log(newStuff.value)
    const response = await axios.post("/user/addSysUser", newStuff.value);
    console.log(response)
    if (response.data.code == 200) {
        toast.add({ severity: 'info', summary: 'Success', detail: "帐号新建成功", life: 3000 });
        addStuffDialog.value = false;
        getData();
    }
    /* console.log(recruct.value.name)
    console.log(recruct.value.phone.replaceAll("-", ""))
    console.log(recruct.value.email)
    console.log(recruct.value.dept.id)
    console.log(recruct.value.status.value) */
    /* addStuffDialog.value = false */
};
</script>

<template>
    <Toast />
    <div class="grid">
        <div class="col-12">
            <div class="card">
                <h5>员工信息</h5>
                <DataTable ref="dt" v-model:selection="selectedStuffs" v-model:editingRows="editingRows" :value="sysUser"
                    :paginator="true" class="p-datatable-gridlines" :rows="5" dataKey="id" :rowHover="true"
                    v-model:filters="filters1" filterDisplay="menu" :loading="loading" :filters="filters1"
                    responsiveLayout="scroll" editMode="row" :pt="{
                        table: { style: 'min-width: 50rem' },
                        column: {
                            bodycell: ({ state }) => ({
                                style: state['d_editing'] && 'padding-top: 0.6rem; padding-bottom: 0.6rem'
                            })
                        }
                    }" @row-edit-save="onRowEditSave" :globalFilterFields="['username', 'deptName']">
                    <template #header>
                        <div class="flex justify-content-between flex-column sm:flex-row">
                            <Button type="button" icon="pi pi-filter-slash" label="Clear" class="p-button-outlined mb-2"
                                @click="clearFilter1()" />
                            <span class="p-input-icon-left mb-2">
                                <i class="pi pi-search" />
                                <InputText v-model="filters1['global'].value" placeholder="Keyword Search"
                                    style="width: 100%" />
                            </span>
                        </div>
                        <div style="text-align: right">
                            <span class="">
                                <Button text icon="pi pi-plus" label="添加员工" @click="openNew" />
                                <Button label="删除员工" text icon="pi pi-trash" severity="danger"
                                    @click="confirmDeleteSelected" :disabled="!selectedStuffs || !selectedStuffs.length" />
                            </span>
                            <Button type="button" icon="pi pi-external-link" label="导出" @click="exportCSV($event)" />
                        </div>

                    </template>
                    <template #empty> No customers found. </template>
                    <template #loading> Loading customers data. Please wait. </template>
                    <Column selectionMode="multiple" headerStyle="width: 3rem"></Column>
                    <Column field="username" header="Name" style="min-width: 12rem">
                        <template #body="{ data }">
                            {{ data.realName }}
                        </template>
                        <!-- <template #editor="{ data, field }">
                            <InputText v-model="data[field]" />
                        </template> -->
                        <template #filter="{ filterModel }">
                            <InputText type="text" v-model="filterModel.value" class="p-column-filter"
                                placeholder="Search by name" />
                        </template>
                    </Column>
                    <Column field="gender" header="性别" filterField="deptId" style="min-width: 12rem">
                        
                    </Column>
                    <Column field="deptId" header="部门" filterField="deptId" style="min-width: 12rem">
                        <template #editor="{ data, field }">
                            <Dropdown v-model="data[field]" :options="deptList" optionLabel="name" optionValue="id"
                                placeholder="Select a Status">
                                <template #option="slotProps">
                                    <Tag :value="slotProps.option.name" :severity="getStatusLabel(slotProps.option.name)" />
                                </template>
                            </Dropdown>
                        </template>
                        <template #body="{ data }">
                            {{ data.deptName }}
                        </template>
                        <template #filter="{ filterModel }">
                            <Dropdown v-model="filterModel.value" :options="deptList" optionLabel="name" optionValue="id"
                                placeholder="Select One" class="p-column-filter" showClear>
                                <template #option="slotProps">
                                    <Tag :value="slotProps.option.name" :severity="getStatusLabel(slotProps.option)" />
                                </template>
                            </Dropdown>
                        </template>
                    </Column>
                    <Column field="status" header="状态" filterField="status" style="min-width: 12rem">
                        <template #editor="{ data, field }">
                            <Dropdown v-model="data[field]" :options="statuses" optionLabel="label" optionValue="value"
                                placeholder="Select a Status">
                                <template #option="slotProps">
                                    <Tag :value="slotProps.option.label"
                                        :severity="getStatusLabel(slotProps.option.value)" />
                                </template>
                            </Dropdown>
                        </template>
                        <template #body="{ data }">
                            <Tag :value="data.statusName" :severity="getStatusLabel(data.status)" />
                            <!-- {{ data.statusName }} -->
                        </template>
                        <template #filter="{ filterModel }">
                            <Dropdown v-model="filterModel.value" :options="statuses" optionLabel="label"
                                optionValue="value" placeholder="Select One" class="p-column-filter" showClear>
                                <template #option="slotProps">
                                    <Tag :value="slotProps.option.label"
                                        :severity="getStatusLabel(slotProps.option.value)" />
                                </template>
                            </Dropdown>
                        </template>
                    </Column>
                    <Column :rowEditor="true" style="width: 10%; min-width: 8rem" bodyStyle="text-align:center"></Column>
                </DataTable>
            </div>
        </div>
        <Dialog v-model:visible="addStuffDialog" :style="{ width: '450px' }" header="员工信息录入" :modal="true" class="p-fluid">
            <div class="field">
                <label for="username">用户名(登录名)</label>
                <InputText id="username" v-model="recruct.username" required="true" autofocus
                    :class="{ 'p-invalid': submitted && !recruct.username }" />
                <small class="p-error" v-if="submitted && !recruct.username">请填写用户名</small>
            </div>
            <div class="field">
                <label for="password">密码</label>
                <InputText id="password" v-model="recruct.password" required="true" autofocus
                    :class="{ 'p-invalid': submitted && !recruct.password }" />
                <small class="p-error" v-if="submitted && !recruct.password">请填写密码</small>
            </div>
            <div class="field">
                <label for="realName">姓名</label>
                <InputText id="realName" v-model="recruct.realName" required="true" autofocus
                    :class="{ 'p-invalid': submitted && !recruct.realName }" />
                <small class="p-error" v-if="submitted && !recruct.realName">请填写姓名</small>
            </div>
            <div class="field">
                <label for="gender">性别</label>
                <Dropdown id="gender" v-model="recruct.gender" :options="genders" optionLabel="label" optionValue="value"
                        autofocus placeholder="选择性别" :class="{ 'p-invalid': submitted && !recruct.gender }">
                    </Dropdown>
                <small class="p-error" v-if="submitted && !recruct.gender">请填写性别</small>
            </div>
            <div class="field">
                <label for="realId">身份证号</label>
                <InputText id="realId" v-model="recruct.realId" required="true" autofocus
                    :class="{ 'p-invalid': submitted && !recruct.realId }" />
                <small class="p-error" v-if="submitted && !recruct.realId">请填写身份证</small>
            </div>
            <div class="field">
                <label for="name">电话号码</label>
                <InputText id="phone" v-model="recruct.phone" required="true" autofocus
                    :class="{ 'p-invalid': submitted && !recruct.phone }" />
                <small class="p-error" v-if="submitted && !recruct.phone">请填写电话号码</small>
            </div>
            <div class="formgrid grid">
                <div class="field col">
                    <label for="inventoryStatus" class="mb-3">工作部门</label>
                    <Dropdown id="inventoryStatus" v-model="recruct.dept" :options="deptList" optionLabel="name" autofocus
                        placeholder="选择工作部门(角色)" :class="{ 'p-invalid': submitted && !recruct.dept }">
                        <template #value="slotProps">
                            <div v-if="slotProps.value && slotProps.value.value">
                                <Tag :value="slotProps.value.name" :severity="getStatusLabel(slotProps.value)" />
                            </div>
                            <div v-else-if="slotProps.value && !slotProps.value.value">
                                <Tag :value="slotProps.value.name" :severity="getStatusLabel(slotProps.value)" />
                            </div>
                            <span v-else>
                                {{ slotProps.placeholder }}
                            </span>
                        </template>
                    </Dropdown>
                    <small class="p-error" v-if="submitted && !recruct.dept">请选择部门</small>
                </div>
                <div class="field col">
                    <label for="inventoryStatus" class="mb-3">帐号状态</label>
                    <Dropdown id="inventoryStatus" v-model="recruct.status" :options="statuses" optionLabel="label"
                        autofocus placeholder="选择状态" :class="{ 'p-invalid': submitted && !recruct.status }">
                        <template #value="slotProps">
                            <div v-if="slotProps.value && slotProps.value.value">
                                <Tag :value="slotProps.value.label" :severity="getStatusLabel(slotProps.value.value)" />
                            </div>
                            <div v-else-if="slotProps.value && !slotProps.value.value">
                                <Tag :value="slotProps.value.label" :severity="getStatusLabel(slotProps.value.value)" />
                            </div>
                            <span v-else>
                                {{ slotProps.placeholder }}
                            </span>
                        </template>
                    </Dropdown>
                    <small class="p-error" v-if="submitted && !recruct.status">请选择帐号状态</small>
                </div>
            </div>
            <template #footer>
                <Button label="Cancel" icon="pi pi-times" text @click="hideDialog" />
                <Button label="Save" icon="pi pi-check" text @click="saveProduct" />
            </template>
        </Dialog>
        <Dialog v-model:visible="deleteStuffsDialog" :style="{ width: '450px' }" header="Confirm" :modal="true">
            <div class="confirmation-content">
                <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
                <span>确认删除所选员工吗?</span>
            </div>
            <template #footer>
                <Button label="No" icon="pi pi-times" text @click="deleteStuffsDialog = false" />
                <Button label="Yes" icon="pi pi-check" text @click="deleteStuff" />
            </template>
        </Dialog>
    </div>
</template>

<style scoped lang="scss">
::v-deep(.p-datatable-frozen-tbody) {
    font-weight: bold;
}

::v-deep(.p-datatable-scrollable .p-frozen-column) {
    font-weight: bold;
}
</style>
